/**
 * 用户授权
 */
let config = require('../config');
let ErrorUtils = require('../utils/error/ErrorUtils');
//const {systemLogger, con} = require('../logger');
const {errorLogger, infoLogger, con} = require('../config').logger;
let redis = require('../redis');
module.exports = () => {
    return async function (ctx, next) {
        infoLogger.info(">>>>小程序鉴权中间件处理开始");
        //console.log(ctx.request.header);
        let headers = ctx.header;
        if (!headers) {
            ctx.status = 401;
            infoLogger.error('401 url - ' + this.url + 'header不存在');
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
        }
        //headers[config.auth.access_key]==config.auth.access_token)
        if (!headers.hasOwnProperty(config.auth.access_key)) {
            ctx.status = 401;
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
            infoLogger.info('401 url - ', this.url);
        }
        let aceessToken = headers[config.auth.access_key];
        let userInfo = await redis.hgetall(`${config.auth.wechatLoginPrefix}${aceessToken}`);
        if (!userInfo || JSON.stringify(userInfo) == '{}') {
            infoLogger.info('401 userinfo- ', userInfo);
            infoLogger.info('401 url - ', this.url);
            ctx.status = 401;
            ctx.status = 401;
            ErrorUtils.throwApiError(ErrorUtils.AUTH_FAIL);
        } else {
            ctx.currentUser = userInfo;
            await redis.expire(`${config.auth.wechatLoginPrefix}${aceessToken}`, config.auth.wechatTtl);
            await next();
            infoLogger.info(">>>>小程序鉴权中间件处理结束");
        }
    }
};

